package com.sparrow.config.property;

import org.springframework.core.env.PropertySource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 外部配置文件资源
 * 方便在不需要打包的情况下直接修改配置文件之后重启生效配置
 */
public class ExternalFilePropertySource extends PropertySource<Properties> {

    private static final String prefix = "sparrow.";

    private boolean canLoad = false;

    public ExternalFilePropertySource() {
        super(prefix, new Properties());
        try {
            File file = new File("resources/config/sparrow.properties");
            if(file.exists()){
                super.source.load(new FileInputStream(file));
                canLoad = true;
            }else{
                String absolutePath = file.getAbsolutePath();
                logger.warn(absolutePath);
                logger.warn("config file is not find.");
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public Object getProperty(String name) {
        if(!name.startsWith(prefix) || !canLoad){
            return null;
        }
        return super.source.getProperty(name);
    }
}
